<template>
  <section>
    <div class="container">
      <div class="filter-container">
        <!-- <common-input @keyup.enter.native="handleFilter" class="w200" placeholder="专场关键字" v-model="keyword" /> -->

        <common-input @keyup.enter.native="handleFilter" class="w200 ml10" placeholder="关键字"
          v-model="listQuery.keyword" />
        <el-button size="mini" class="ml10" type="primary" icon="el-icon-search" @click="handleFilter">搜索</el-button>
        <el-button @click="addAccount" type="primary" size="mini" class="btn">新增</el-button>
        <!-- <el-button size="mini" class="ml10" @click="handleCreate" type="primary" icon="el-icon-plus">新增</el-button> -->
      </div>

      <el-table :data="tableData" style="width:100%" max-height="720" class="shop_table_list" :cell-style="tc"
        :header-cell-style="tccolor">
        <el-table-column prop="id" label="角色ID"></el-table-column>
        <el-table-column prop="roleName" label="角色名称">
          <template slot-scope="scope">
            {{ scope.row.roleName }}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态">
          <template slot-scope="scope">
            {{ scope.row.status === 0 ? "正常" : "禁用" }}
            <!-- <el-switch
          @change = "switchStatus($event,scope.row.id)"
          v-model="scope.row.status"
          active-color="#13ce66"
          inactive-color="#ff4949"
          active-value="1" inactive-value="0">
        </el-switch> -->
          </template>
        </el-table-column>
        <!-- <el-table-column prop="last_time_text" label="最近登录时间"></el-table-column> -->
        <el-table-column prop="time" label="操作">
          <template slot-scope="scope">
            <el-button type="primary" size="mini" @click="openDialog(scope.row)"
              style="margin-right:10px">修改</el-button>
            <!-- <el-button slot="reference" type="primary" @click="openDialog(scope.row.id)" size="mini">权限管理</el-button> -->
            <el-popconfirm title="是否要删除此账号 ?" @confirm="deleteRole(scope.row.id)">
              <el-button slot="reference" type="primary" size="mini">删除角色</el-button>
            </el-popconfirm>
            <!-- <el-button slot="reference" type="primary" @click="deleteRole(scope.row.id)" size="mini">删除</el-button> -->
          </template>
        </el-table-column>
      </el-table>
      <el-col :span="24">
        <div class="pagination">
          <el-pagination background @current-change="pageChange" :current-page="listQuery.pageNum"
            :page-size="listQuery.pageSize" layout="total, prev, pager, next, jumper" :total="total"></el-pagination>
        </div>
      </el-col>

      <el-dialog :title="dialogText" :visible.sync="dialogVisibleAdd" width="50%" :close-on-click-modal="false"
        @closed="cancel">
        <el-form :model="formDataAdd" :rules="rulesAdd" ref="formAdd" label-width="100px">
          <el-row>
            <el-col :span="12">
              <el-form-item label="角色名称" prop="roleName">
                <el-input v-model="formDataAdd.roleName" placeholder="请输入角色名称" type="text"></el-input>
              </el-form-item>
            </el-col>

            <el-col :span="12">
              <el-form-item prop="roleKey">
                <span slot="label">
                  <el-tooltip content="控制器中定义的权限字符，如：@PreAuthorize(`@ss.hasRole('admin')`)" placement="top">
                    <i class="el-icon-question"></i>
                  </el-tooltip>
                  权限字符
                </span>
                <el-input v-model="formDataAdd.roleKey" placeholder="请输入权限字符" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="显示顺序" prop="roleSort">
                <el-input-number v-model="formDataAdd.roleSort" placeholder="请输入显示顺序" type="text"
                  :min="0"></el-input-number>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="账号状态" prop="status">

                <el-radio-group v-model="formDataAdd.status">
                  <el-radio :label="1">禁用</el-radio>
                  <el-radio :label="0">启用</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="菜单权限">
                <el-checkbox v-model="menuExpand" @change="handleCheckedTreeExpand($event, 'menu')">展开/折叠</el-checkbox>
                <el-checkbox v-model="menuNodeAll"
                  @change="handleCheckedTreeNodeAll($event, 'menu')">全选/全不选</el-checkbox>
                <el-checkbox v-model="form.menuCheckStrictly"
                  @change="handleCheckedTreeConnect($event, 'menu')">父子联动</el-checkbox>
                <el-tree class="tree-border" :data="menuOptions" show-checkbox ref="menu" node-key="id"
                  :check-strictly="!form.menuCheckStrictly" empty-text="加载中，请稍候" :props="defaultProps"></el-tree>
                <!-- <el-button @click="getCheckedNodes">通过 node 获取</el-button> -->
              </el-form-item>
            </el-col>
            <!-- <el-form-item label="合作人ID" prop="partnerId">
          <el-input v-model="formDataAdd.partnerId" placeholder="请输入合作人ID" type="text"></el-input>
        </el-form-item>
        <el-form-item label="小店ID" prop="sellerId">
          <el-input v-model="formDataAdd.sellerId" placeholder="请输入小店ID" type="text"></el-input>
        </el-form-item> -->
            <el-col :span="24">
              <el-form-item label="备注" prop="remark">
                <el-input v-model="formDataAdd.remark" type="textarea" placeholder="请输入备注信息"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item class="end" style="display: flex; justify-content: flex-end">
                <el-button type="primary" @click="submitAdd">确定</el-button>

                <el-button @click="cancel">取消</el-button>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </el-dialog>
    </div>
  </section>
</template>

<script>
import { roleCreate, roleUpdate, roleDelete, roleListAll, roleList, roleUpdateStatus, updateStatus, roleDetails } from '@/api/admin'
import { treeList } from '@/api/menu'
export default {

  data() {
    return {
      tableData: [],
      menuExpand: false,
      menuNodeAll: false,
      dialogText: '增加角色',
      form: {
        page: 1
      },
      listQuery: {
        // pageNum: 1,
        // pageSize: 20,
        keyword: undefined,
        // partnerId: undefined,
        // sellerId: 0,
      },
      keyword: '',
      total: 0,
      dialogVisible: false,
      dialogVisibleAdd: false,
      rules: {
        old_password: [
          { required: true, message: '请输入旧密码', trigger: 'blur' },
        ],
        new_password: [
          { required: true, message: '请输入新密码', trigger: 'blur' },
          { min: 8, message: '密码至少为8个字符', trigger: 'blur' }
        ],

        confirm_new_password: [
          { required: true, message: '请输入新密码', trigger: 'blur' },
          { validator: this.checkConfirmPassword, trigger: 'blur' }
        ]
      },
      rulesAdd: {
        roleName: [
          { required: true, message: '角色名必填', trigger: 'blur' },

        ],
        roleKey: [
          { required: true, message: "权限字符不能为空", trigger: "blur" }
        ],
      },
      typeList: [
        { id: 0, name: '平台用户' },
        { id: 1, name: '合伙人用户' },
        { id: 2, name: '小店用户' }
      ],
      formData: {
        id: '',
        old_password: '',
        new_password: '',
        confirm_new_password: ''
      },
      formDataAdd: {
        id: '',
        roleName: '',
        roleKey: '',
        roleSort: 0,
        dataScope: '',
        status: 0,
        remark: '',
        menuIds: []

      },
      defaultProps: {
        children: "children",
        label: "menuName"
      },
      // 菜单列表
      menuOptions: [],
    }
  },
  mounted() {
    this.getRoleList()
    this.getMenuTreeselect()
    
  },
  methods: {
    /** 查询菜单树结构 */
    getMenuTreeselect() {
      // this.$refs.menu.setCheckedNodes([])
      treeList().then(response => {
        this.menuOptions = response.data;
        console.log(response.data,'############')
        
      });
    },
    // 所有菜单节点数据
    getMenuAllCheckedKeys() {
      // 目前被选中的菜单节点
      let checkedKeys = this.$refs.menu.getCheckedKeys();
      // 半选中的菜单节点
      let halfCheckedKeys = this.$refs.menu.getHalfCheckedKeys();
      checkedKeys.unshift.apply(checkedKeys, halfCheckedKeys);
      return checkedKeys;
    },
    // 树权限（展开/折叠）
    handleCheckedTreeExpand(value, type) {
      if (type == 'menu') {
        let treeList = this.menuOptions;
        for (let i = 0; i < treeList.length; i++) {
          this.$refs.menu.store.nodesMap[treeList[i].id].expanded = value;
        }
      } else if (type == 'dept') {
        let treeList = this.deptOptions;
        for (let i = 0; i < treeList.length; i++) {
          this.$refs.dept.store.nodesMap[treeList[i].id].expanded = value;
        }
      }
    },
    // 树权限（全选/全不选）
    handleCheckedTreeNodeAll(value, type) {
      if (type == 'menu') {
        this.$refs.menu.setCheckedNodes(value ? this.menuOptions : []);
      } else if (type == 'dept') {
        this.$refs.dept.setCheckedNodes(value ? this.deptOptions : []);
      }
    },
    // 树权限（父子联动）
    handleCheckedTreeConnect(value, type) {
      if (type == 'menu') {
        this.form.menuCheckStrictly = value ? true : false;
      } else if (type == 'dept') {
        this.form.deptCheckStrictly = value ? true : false;
      }
    },
    // 状态切换
    switchStatus(e, id) {
      console.log(e, id)
      let data = {
        id: id,
        status: 0
      }
      if (e) {
        data.status = 1
      } else {
        data.status = 0
      }
      roleUpdateStatus(data).then(res => {
        console.log(res)
        if (res.code === 200) {
          this.$message.success('修改成功')
          this.getRoleList()
        } else {
          this.$message.error(res.message)
        }
      })


    },
    // 条件查询
    handleFilter() {
      // this.listQuery.pageNum = 1;
      this.getAdminList();
    },
    tc() {
      return "text-align:center; color:#333333; font-size:12px;";
    },
    tccolor() {
      return "text-align:center;background-color:#f5f5f5; font-size:14px;";
    },
    // 取消
    cancel() {
      this.dialogVisibleAdd = false
      // location.reload();
          this.$refs.menu.setCheckedNodes([]);
      // this.$refs['form'].clearValidate()
      // this.formData = {
      //   old_password: '',
      //   new_password: '',
      //   confirm_new_password: ''
      // }
    },
    // 提交信息
    submitAdd() {
      console.log(this.formDataAdd)
      console.log(this.$refs.menu.getCheckedNodes())
      let treeData = this.$refs.menu.getCheckedNodes()
      let menuIds = []
      treeData.forEach(item => {
        menuIds.push(item.id)
      })
      this.formDataAdd.menuIds = menuIds

      this.$refs['formAdd'].validate(valid => {
        if (valid) {
          if (this.formDataAdd.id) {
            roleUpdate(this.formDataAdd).then(res => {
              console.log(res)
              if (res.code === 200) {
                this.$message.success('修改成功')

                this.dialogVisibleAdd = false
                this.getRoleList()
              } else {
                this.$message.error(res.message)
              }
            })
          } else {
            roleCreate(this.formDataAdd).then(res => {
              console.log(res)
              if (res.code === 200) {
                this.$message.success('创建成功')
                this.getRoleList()
                this.dialogVisibleAdd = false
              } else {
                this.$message.error(res.message)
              }
            })
          }
          location.reload();
          this.$refs.menu.setCheckedNodes([]);
        }
      })
    },
    // 删除角色（暂时有问题）
    deleteRole(id) {
      // let data = []
      // data.push(id)
      // console.log(data)
      // let idArr = {
      //   ids: data
      // }

      roleDelete(id).then(res => {

        if (res.code === 200) {
          // res.data.data.forEach(item => {
          //   item.last_time_text = item.last_time || '无'
          // })
          this.$message.success(res.message)
          this.getRoleList()
        } else {
          this.$message.error(res.message)
        }
      })
    },
    //  获取角色列表
    getRoleList() {
      roleListAll(this.listQuery).then(res => {
        if (res.code === 200) {
          // res.data.data.forEach(item => {
          //   item.last_time_text = item.last_time || '无'
          // })
          console.log(res)
          this.tableData = res.data
          this.total = res.data.total
        } else {
          this.$message.error(res.message)
        }
      })
    },

    // 修改弹窗
    openDialog(row) {
      this.dialogText = '修改角色'
      let ids = []
     
      
      // this.getMenuTreeselect();
      roleDetails(row.id).then(res => {
        console.log(res)
        if (res.code === 200) {
          // this.$message.success('修改成功')
          this.formDataAdd = res.data
          if(res.data.menuIds){
            res.data.menuIds.forEach(item => {
              let aa = { id: item }
              ids.push(aa)
            });
            
            // this.$refs.menu.setCheckedNodes(ids)
            
          }
          if(ids.length){
            console.log(ids, "id集合")
            this.$refs.menu.setCheckedNodes(ids);
          }


          this.dialogVisibleAdd = true
        } else {
          this.$message.error(res.message)
        }
      })
      this.formDataAdd = {
        id: row.id,
        roleName: row.roleName,
        roleKey: row.roleKey,
        roleSort: row.roleSort,
        dataScope: row.dataScope,
        status: row.status,
        remark: row.remark,

      }
      this.dialogVisibleAdd = true
      this.formData.id = row.id
      
    },
    pageChange(page) {
      this.form.page = page
      this.getAdminList()
    },
    // 添加弹窗
    addAccount() {
      this.dialogText = '新增角色'
      this.formDataAdd = {
        id: '',
        roleName: '',
        roleKey: '',
        roleSort: 0,
        dataScope: '',
        status: 0,
        remark: '',

      }
      this.dialogVisibleAdd = true
      // this.getMenuTreeselect();
    },

  }
}
</script>

<style lang="scss" scpoed>
.container {

  // width:100% !important;
  // padding: 20px !important;
  .btn {
    margin-bottom: 20px;

    .btn-box {
      display: flex;
    }
  }

  .pagination {
    margin-top: 20px;
    float: right;
  }
}

.tree-border {
  margin-top: 5px;
  border: 1px solid #e5e6e7;
  background: #FFFFFF none;
  border-radius: 4px;
}
</style>
